<template>
  <div class="admin-login-container">
    <el-card class="login-card">
      <h2 class="login-title">管理员登录</h2>
      <div class="login-tip">
        <el-alert
          title="仅限管理员访问"
          type="warning"
          :closable="false"
          show-icon
          style="margin-bottom: 20px;"
        >
          <template #default>
            此页面仅供系统管理员使用，需要管理员权限才能访问
          </template>
        </el-alert>
      </div>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px" @keyup.enter="onLogin">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入管理员账号" clearable />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="login-btn" @click="onLogin" :loading="loading" style="width:100%">
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { adminLogin } from '../../api/admin'
import { useAdminStore } from '../../stores/admin'
import { useAdminAuth } from '../../composables/useAdminAuth'

const router = useRouter()
const adminStore = useAdminStore()
const { isAdminLoggedIn } = useAdminAuth()

// 监听认证清除事件
const handleAuthCleared = () => {
  // 认证被清除时，确保不会显示"已登录"消息
  console.log('管理员认证已清除')
}

// 如果已经登录，直接跳转到仪表板
onMounted(() => {
  // 先检查并清理过期的管理员信息
  adminStore.checkExpire()
  
  // 添加事件监听器
  window.addEventListener('admin-auth-cleared', handleAuthCleared)
  
  // 使用 nextTick 确保响应式更新完成后再检查
  setTimeout(() => {
    if (isAdminLoggedIn.value) {
      ElMessage.info('您已登录，正在跳转到管理员仪表板')
      router.push('/admin/dashboard')
    }
  }, 100)
})

onUnmounted(() => {
  // 清理事件监听器
  window.removeEventListener('admin-auth-cleared', handleAuthCleared)
})

const formRef = ref()
const loading = ref(false)
const form = ref({
  username: '',
  password: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度为2-20个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为6个字符', trigger: 'blur' }
  ]
}

const onLogin = async () => {
  await formRef.value?.validate()
  loading.value = true
  try {
    const res = await adminLogin({
      username: form.value.username,
      password: form.value.password
    })
    console.log('登录响应:', res)
    
    if (res && res.data && res.data.token) {
      // 检查用户角色是否为管理员
      if (res.data.role !== 1) {
        ElMessage.error('权限不足，需要管理员权限')
        loading.value = false
        return
      }
      // 检查用户状态是否正常 status=0表示正常
      if (res.data.status !== 0) {
        ElMessage.error('账号状态异常，请联系系统管理员')
        loading.value = false
        return
      }
      ElMessage.success('登录成功')
      // 构造管理员信息对象
      const adminInfo = {
        username: res.data.username,
        userId: res.data.userId,
        status: res.data.status,
        role: res.data.role,
        token: res.data.token
      }
      // 存储管理员信息到store并设置有效期为72小时
      useAdminStore().setAdminInfo(adminInfo, 72)
      // 跳转到管理员仪表板
      router.push('/admin/dashboard')
    } else {
      ElMessage.error('登录失败，请检查用户名和密码')
    }
  } catch (error) {
    console.error('登录错误:', error)
    ElMessage.error('登录失败，请检查网络连接或稍后重试')
  }
  loading.value = false
}
</script>

<style scoped>
.admin-login-container {
  height:100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: transparent;
}

.login-card {
  width: 380px;
  padding: 36px 32px 24px 32px;
  border-radius: 18px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  box-shadow: 0 4px 24px 0 rgba(90, 80, 200, 0.16), 0 1.5px 6px 0 rgba(90,80,200,0.10);
  background: #fff;
}

.login-title {
  text-align: center;
  color: #5b6ee1;
  font-size: 26px;
  font-weight: bold;
  margin-bottom: 28px;
}
.login-btn {
  width: 100%;
  height: 44px;
  font-size: 16px;
  background: #5b6ee1 !important;
  border: none !important;
}
.login-btn:active,
.login-btn:focus {
  background: #3a3e99 !important;
}
</style>
